package com.shangyueshang.controller;

import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import com.shangyueshang.request.LoginDTO;
import com.shangyueshang.response.HttpResult;
import com.shangyueshang.security.JwtAuthenticationToken;
import com.shangyueshang.utils.SecurityUtil;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author: JokeyZheng
 * @email: zhengjingfeng@ruqimobility.com
 * @created: 2022/1/6 11:09
 * @version: v1.0.0
 */
@RestController
public class SysLoginController {
	
	@Resource
	private Producer producer;
	
	@Resource
	private AuthenticationManager authenticationManager;
	
	/**
	 * 获取验证码
	 *
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@GetMapping("captcha.jpg")
	public void captcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
		response.setHeader("Cache-control", "no-store, no-cache");
		response.setContentType("image/jpeg");
		//生成文字验证码
		String text = producer.createText();
		//生成图片验证码
		BufferedImage image = producer.createImage(text);
		//fixme 保存验证码到session中
		request.getSession().setAttribute(Constants.KAPTCHA_SESSION_KEY, text);
		ServletOutputStream out = response.getOutputStream();
		ImageIO.write(image, "jpg", out);
		IOUtils.closeQuietly(out);
	}
	
	/**
	 * 登录
	 *
	 * @param request
	 * @param loginDTO
	 * @return
	 */
	@PostMapping("/login")
	public HttpResult<JwtAuthenticationToken> login(HttpServletRequest request, @Valid @RequestBody LoginDTO loginDTO) {
		String username = loginDTO.getAccount();
		String password = loginDTO.getPassword();
		String captcha = loginDTO.getCaptcha();
		//从session中获取之前保存的验证码与前台传来的验证码进行匹配
		Object kaptCha = request.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
		if (kaptCha == null) {
			return HttpResult.fail("验证码已失效");
		}
		if (!kaptCha.equals(captcha)) {
			return HttpResult.fail("验证码不正确");
		}
		//执行登录，生成token返回
		JwtAuthenticationToken jwtAuthenticationToken = SecurityUtil.login(request, username, password, authenticationManager);
		return HttpResult.ok(jwtAuthenticationToken);
	}
}
